import { _decorator, Button, Color, Component, instantiate, Label, Node, RichText, v3 } from 'cc';
import { DevelopState, Soldier } from '../entity/Soldier';
import { Utils } from '../common/Utils';
import { UserInfo } from '../common/UserInfo';
import VillageApi from '../api/VillageApi';
import { Events } from '../entity/Events';
import { UIManager } from '../common/UIManager';
import { DiamondConsume, EventOper } from '../entity/Buildings';
import { EventManager } from '../event/EventManager';
import { EventType } from '../settings/const';
const { ccclass, property } = _decorator;

@ccclass('DevelopBlock')
export class DevelopBlock extends Component {
 
    @property(Label)
    stateStr: Label
    @property(Node)
    buildingLabel: Node
    @property(Node)
    buildingLayout: Node
    @property(Label)
    wood: Label
    @property(Label)
    mud: Label
    @property(Label)
    iron: Label
    @property(Label)
    food: Label
    @property(Label)
    time: Label
    @property(Node)
    developBtn: Node
    @property(Label)
    countTittle: Label
    @property(Label)
    countTime: Label
    @property(Node)
    speedBtn: Node

    private red:Color = Utils.Red
    private soldierData: Soldier
    private offTime: number = 0
    start() {
        this.developBtn.on(Node.EventType.TOUCH_END, this.onDevelop, this)
        this.speedBtn.on(Node.EventType.TOUCH_END, this.onSpeed, this)
    }

    setData(soldier: Soldier) {
        this.soldierData = soldier
        let buildings = soldier.getRequireBuilding()

        let event = soldier.getDevelopingEvent()
        if (event) {
            this.developBtn.active = false
            this.countTittle.node.active = true
            this.countTime.node.active = true
            this.speedBtn.active = true
            // 开始研发的倒计时
            this.countDown(event)
        } else {
            this.developBtn.active = true
            this.countTittle.node.active = false
            this.countTime.node.active = false
            this.speedBtn.active = false
        }

        if (soldier.isCanDevelop) {
            this.stateStr.string = '可研发'
        } else {
            this.stateStr.color = this.red
            let str = ''
            let once = false
            for (let b of buildings) {
                if (b.isLack) {
                    if (!once) {
                        str += '需要'
                        once = true
                    }
                    str += b.name + '、'
                }
            }

            if (!soldier.isResEnough) {
                str += '资源不足、'
            }

            str = str.substring(0, str.length - 1)

            this.stateStr.string = str

            this.developBtn.getComponent(Button).interactable = false
        }


        this.buildingLayout.destroyAllChildren()
        for (let b of buildings) {
            let node = instantiate(this.buildingLabel)
            node.position = v3(0, 0, 0)
            let label = node.getComponent(Label)
            if (b.isLack) {
                label.string = `${b.name}等级${b.level}`
                label.color = this.red
                
            } else {
                label.string = `${b.name}等级${b.level}`

            }

            this.buildingLayout.addChild(node)
        }

        this.wood.string = Utils.bigNumberTransform(soldier.studyWood)
        this.mud.string = Utils.bigNumberTransform(soldier.studyMud)
        this.iron.string = Utils.bigNumberTransform(soldier.studyIron)
        this.food.string = Utils.bigNumberTransform(soldier.studyFood)

        let villageData = UserInfo.instance.villageData
        let food = villageData.res.food_reserve
        let iron = villageData.res.iron_reserve
        let wood = villageData.res.wood_reserve
        let mud = villageData.res.mud_reserve

        if (food < soldier.studyFood) {
            this.food.color = this.red
        }
        if (iron < soldier.studyIron) {
            this.iron.color = this.red
        }
        if (wood < soldier.studyWood) {
            this.wood.color = this.red
        }
        if (mud < soldier.studyMud) {
            this.mud.color = this.red
        }


        this.time.string = Utils.secondToStr(Math.floor(soldier.studyTime / UserInfo.instance.speed))
    }


    countDown(event: Events) {
        this.unschedule(this.updateTime)
        if (!event) {
            return
        }

        let eStartTime = event.eStartTime
        this.offTime = eStartTime - Math.floor(UserInfo.instance.serverTime / 1000)
        if (this.offTime <= 0) {
            return
        }

        this.countTime.string = Utils.secondToStr(this.offTime)
        this.schedule(this.updateTime, 1, this.offTime - 1)
    }

    updateTime() {
        this.offTime--
        this.countTime.string = Utils.secondToStr(this.offTime)

        if (this.offTime <= 0) {
            // 倒计时完成
            // 清除事件，刷新页面
            this.soldierData.developComplete()
        }
    }

    async onDevelop() {
        if (!this.soldierData.isCanDevelop) {
            UIManager.instance.tip('条件不满足')
            return
        }
        await UIManager.instance.showLoading()
        let res = await VillageApi.studying(this.soldierData.soldierIndex + 1)
        UIManager.instance.closeLoading()
        console.log(`研发新兵种：id=${this.soldierData.id}， ${this.soldierData.name}，`)
        await UserInfo.instance.refreshVillageDetail()

        this.setData(this.soldierData)

        // res = await VillageApi.getVillageEvents(EventType.study)
        // console.log(res)
    }

    async onSpeed() {
        let event = this.soldierData.getDevelopingEvent()
        let param = {
            ac: EventOper.SPEED_BUILD,
            eid: event.eHandle
        }

        await UIManager.instance.showLoading()
        let res = await VillageApi.eventOper(param)
        UIManager.instance.closeLoading()
        console.log(`加速研发，ac =${param.ac} ,del =${param.eid} `, res)

        // 清除事件，刷新页面
        this.soldierData.developComplete()

        // 记得扣除砖石哦 -- 已经改为加速道具了
        // UserInfo.instance.diamond -= DiamondConsume.BUILD
        // EventManager.instance.emit(EventManager.EventType.RefreshDiamond,  UserInfo.instance.diamond)
    }
}


